

#import "CBLEDataMnger.h"
#import "CBLEDataParse.h"
#import "JCDataConvert.h"
#import "CBLECenterMnger.h"

#define  CMD_SEND_INTERVAL 0.03  //蓝牙指令发送间隔,发送频率过快会导致设备有时处理不过来

@interface CDataPheralInfo()<CBPeripheralDelegate>
@property(nonatomic,strong)CBUUID  *uuidReadMacAddr;
@property(nonatomic,strong)CBUUID  *uuidWristCmdAckPush;
@property(nonatomic,strong)CBUUID  *uuidWristReadAck;

@property(nonatomic,strong)CBUUID  *uuidWR;
@property(nonatomic,strong)CBUUID  *uuidWRWrite;
@property(nonatomic,strong)CBUUID  *uuidWRIndicate;
@property(nonatomic,strong)CBUUID  *uuidWRWriteOTAData;

//写特征
@property(nonatomic,strong)CBCharacteristic *writeCmdAckChrtcs;//写
@property(nonatomic,strong)CBCharacteristic *readCmdChrtcs;//读


@property(nonatomic,strong)CBCharacteristic *writeOTAWithRespCharac;
@property(nonatomic,strong)CBCharacteristic *writeOTAWithoutRespCharac;

//写wifi名称特征
@property(nonatomic,strong)CBCharacteristic *writeSsidCmdAckChrtcs;
//写wifi密码特征
@property(nonatomic,strong)CBCharacteristic *writePassCmdAckChrtcs;

@end


@implementation CDataPheralInfo
// 实现 NSCoding 协议方法
- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:self.devName forKey:@"devName"];
    [coder encodeDouble:self.connectTime forKey:@"connectTime"];
    [coder encodeObject:self.adverMacAddr forKey:@"adverMacAddr"];
    [coder encodeInteger:self.productId forKey:@"productId"];
    [coder encodeObject:self.deviceType forKey:@"deviceType"];
    [coder encodeObject:self.productName forKey:@"productName"];
    [coder encodeBool:self.hasMaster forKey:@"hasMaster"];
    [coder encodeBool:self.highVoltage forKey:@"highVoltage"];
    [coder encodeInt:self.wifiType forKey:@"wifiType"];
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super init];
    if (self) {
        self.devName      = [coder decodeObjectForKey:@"devName"];
        self.connectTime  = [coder decodeDoubleForKey:@"connectTime"];
        self.adverMacAddr = [coder decodeObjectForKey:@"adverMacAddr"];
        self.productId    = [coder decodeIntegerForKey:@"productId"];
        self.deviceType   = [coder decodeObjectForKey:@"deviceType"];
        self.productName  = [coder decodeObjectForKey:@"productName"];
        self.hasMaster    = [coder decodeBoolForKey:@"hasMaster"];
        self.highVoltage  = [coder decodeBoolForKey:@"highVoltage"];
        self.wifiType     = [coder decodeIntForKey:@"wifiType"];
    }
    return self;
}

+ (BOOL)supportsSecureCoding
{
    return YES;
}

- (NSString*)fmtBootVer{
    
    NSString *strTip = @"OTA模式";
    if ( !_bIsInOTA ){
        strTip = [NSString stringWithFormat:@"bootver:%@",_strBootVer];
        if ( _strBootVer == nil || _strBootVer.length <= 0 )
            strTip =@" ";
    }
    return strTip;
}


- (BOOL)isSamePheralWithMacAddr:(NSString*)oldMac{
    if (oldMac.length < 17) {
        NSLog(@"不能继续往下执行，字符串长度不对：%@",oldMac);
        return NO;
    }else if(self.adverMacAddr.length < 16){
        NSLog(@"不能继续往下执行，广播的MAC地址不对：%@",self.adverMacAddr);
        return NO;
    }else{
        NSLog(@"oldMac------- %@，newMac-----%@",oldMac,self.adverMacAddr);
    }
    //0405122696d812fc0000
    //FC:12:D8:96:26:11
    NSString *strCur = self.adverMacAddr;
    if ([UIDevice currentDevice].systemVersion.floatValue >= 13.0 && [strCur containsString:@"length"]&& [strCur containsString:@"bytes"]) {
        NSRange rangeTemp = [strCur rangeOfString:@"0x"];
        strCur = [strCur substringFromIndex:rangeTemp.location+rangeTemp.length];
        strCur = [strCur stringByReplacingOccurrencesOfString:@"{" withString:@""];
        strCur = [strCur stringByReplacingOccurrencesOfString:@"}" withString:@""];
    }
    if (strCur.length < 16) {
        NSLog(@"strCur:%@",strCur);
    }
   
    
    NSString *strTemp = [strCur substringWithRange:NSMakeRange(0, 2)];
    NSInteger nNew1 = strtoul([strTemp UTF8String],0,16);

    strTemp = [strCur substringWithRange:NSMakeRange(2, 2)];
    NSInteger nNew2 = strtoul([strTemp UTF8String],0,16);
    
    strTemp = [strCur substringWithRange:NSMakeRange(4, 2)];
    NSInteger nNew3 = strtoul([strTemp UTF8String],0,16);
    
    strTemp = [strCur substringWithRange:NSMakeRange(6, 2)];
    NSInteger nNew4 = strtoul([strTemp UTF8String],0,16);
    
    strTemp = [strCur substringWithRange:NSMakeRange(8, 2)];
    NSInteger nNew5 = strtoul([strTemp UTF8String],0,16);
    
    strTemp = [strCur substringWithRange:NSMakeRange(10, 2)];
    NSInteger nNew6 = strtoul([strTemp UTF8String],0,16);
    
    strTemp = [strCur substringWithRange:NSMakeRange(12, 2)];
    NSInteger nNew7 = strtoul([strTemp UTF8String],0,16);
    
    strTemp = [strCur substringWithRange:NSMakeRange(14, 2)];
    NSInteger nNew8 = strtoul([strTemp UTF8String],0,16);
    
    
    strTemp = [oldMac substringWithRange:NSMakeRange(0, 2)];
    NSInteger nLoc1 = strtoul([strTemp UTF8String],0,16);
    
    strTemp = [oldMac substringWithRange:NSMakeRange(3, 2)];
    NSInteger nLoc2 = strtoul([strTemp UTF8String],0,16);
    
    strTemp = [oldMac substringWithRange:NSMakeRange(6, 2)];
    NSInteger nLoc3 = strtoul([strTemp UTF8String],0,16);
    
    strTemp = [oldMac substringWithRange:NSMakeRange(9, 2)];
    NSInteger nLoc4 = strtoul([strTemp UTF8String],0,16);
    
    strTemp = [oldMac substringWithRange:NSMakeRange(12, 2)];
    NSInteger nLoc5 = strtoul([strTemp UTF8String],0,16);
    
    strTemp = [oldMac substringWithRange:NSMakeRange(15, 2)];
    NSInteger nLoc6 = strtoul([strTemp UTF8String],0,16);
    
    if (nLoc1==nNew1 && nLoc2==nNew2 && nLoc3==nNew3 && nLoc4==nNew4 && nLoc5==nNew5 && (nLoc6+1==nNew6||(nLoc6==255 && nNew1==0))) {
        return YES;
    }

    if( nLoc1 != nNew8 ) return NO;
    if( nLoc2 != nNew7 ) return NO;
    if( nLoc3 != nNew6 ) return NO;
    if( nLoc4 != nNew5 ) return NO;
    if( nLoc5 != nNew4 ) return NO;
    if( nLoc6==255 && nNew3==0) return YES; //特殊情况:0xFF与0X00的比较
    if( nLoc6+1 != nNew3 ) return NO;
    
    return YES;
}

-(BOOL)isSamePheralWithUUID:(NSString*)uuidStr{
    
    NSLog(@"   UUID:::%@,%@\r\n",uuidStr,_peripheral.identifier.UUIDString);
    if ( [_peripheral.identifier.UUIDString isEqualToString:uuidStr] )
        return YES;
    return NO;
}

-(BOOL)isSamePeralWithName:(NSString*)perName{
    if ( [_peripheral.name isEqualToString:perName] ){
        NSLog(@"找到这个设备，但是没有进入OTA模式");
        return NO;
    }
    if ([_peripheral.name isEqualToString:@"PPlusOTA"] || [_peripheral.name isEqualToString:@"LefunOTA"]) {
        return YES;
    }
    return NO;
}

+(instancetype)dataPheral:(CBPeripheral*)pheral advData:(NSDictionary *)advData RSSI:(NSNumber *)RSSI{
    CDataPheralInfo *dataInfo = [[CDataPheralInfo alloc] initWithPheral:pheral advData:advData RSSI:RSSI];
    return dataInfo;
}

-(instancetype)initWithPheral:(CBPeripheral*)pheral advData:(NSDictionary *)advData RSSI:(NSNumber *)RSSI{
    
    if ( self = [super init] ){
        
        _strBootVer = @"";
        _bIsInOTA   = NO;
        _peripheral = pheral;
        _advData    = advData;
        _RSSI       = RSSI;
        
       
        
        if(pheral.name == nil||pheral.name.length == 0){
            _devName = advData[@"kCBAdvDataLocalName"];
        }else{
            _devName = pheral.name;
        }
        //mac地址
        if(advData[@"kCBAdvDataManufacturerData"]){
            _adverMacAddr = [[NSString alloc]initWithData:advData[@"kCBAdvDataManufacturerData"] encoding:NSUTF8StringEncoding];
        }
        //服务数据
        if(advData[@"kCBAdvDataServiceData"]){
            NSData *serviceData = advData[@"kCBAdvDataServiceData"][[CBUUID UUIDWithString:@"0000"]];
            if(serviceData.length >= 5){
                //产品ID
                NSData *productData = [serviceData subdataWithRange:NSMakeRange(0, 2)];
                self.productId = [JCDataConvert dataToInt:productData];
                //是否带主控
                NSData *masterData = [serviceData subdataWithRange:NSMakeRange(2, 1)];
                _hasMaster = [JCDataConvert dataToInt:masterData];
                //高低压
                NSData *hvData = [serviceData subdataWithRange:NSMakeRange(3, 1)];
                _highVoltage = [JCDataConvert dataToInt:hvData];
                
                //设备类型
                NSData *devTypeData = [serviceData subdataWithRange:NSMakeRange(4, 1)];
                NSInteger type = [JCDataConvert dataToInt:devTypeData];
                switch (type) {
                    case 0:
                        self.deviceType = @"Battery";
                        break;
                    case 1:
                        self.deviceType = @"All-In-One";
                        break;
                    case 2:
                        self.deviceType = @"AC Micro-Grid";
                        break;
                    case 3:
                        self.deviceType = @"DC Micro-Grid";
                        break;
                    default:
                        break;
                }
            }
            
        }
        
        NSLog(@"----->mac 地址:%@",_adverMacAddr);
        NSLog(@"----->产品名称:%@",self.productName);
        _uuidReadMacAddr     = [CBUUID UUIDWithString:BLEUUID_SERVER_DEVICE_READMAC];
        _uuidWristCmdAckPush = [CBUUID UUIDWithString:BLEUUID_SERVER_WRIST_CMDACK];
        _uuidWristReadAck    = [CBUUID UUIDWithString:BLEUUID_SERVER_WRIST_READ];
        
        _uuidWR              = [CBUUID UUIDWithString:BLEUUID_SERVER_WR];
        _uuidWRWrite         = [CBUUID UUIDWithString:BLEUUID_SERVER_WR_WRITE];;
        _uuidWRIndicate      = [CBUUID UUIDWithString:BLEUUID_SERVER_WR_INDICATE];
        _uuidWRWriteOTAData  = [CBUUID UUIDWithString:BLEUUID_SERVER_WR_DATA_WRITE];
    }
    return self;
}

-(void)setProductId:(NSInteger)productId
{
    _productId = productId;
    switch (_productId) {
        case 0:
            {
                self.productName = @"XtremeLV1.0";
            }
            break;
        
        case 1:
            {
                self.productName = @"XtremeLV1.0&日月元12KW";
            }
            break;
        case 2:
            {
                self.productName = @"一体机(日月元)";
            }
            break;
        case 21:
            {
                self.productName = @"一体机(迈格瑞能7KW)";
            }
            break;
        case 100:
            {
                self.productName = @"XtremeLV1.0&纳通";
            }
            break;
        case 200:
            {
                self.productName = @"XtremeLV1.0(蓝牙&Wifi同时使用)";
            }
            break;
        case 300:
            {
                self.productName = @"Xcellent Plus(沛城16度电)";
            }
            break;
       
        default:
            break;
    }
}




-(BOOL)isSamePheral:(CBPeripheral*)pheral{
    
    if ( [_peripheral.identifier.UUIDString isEqualToString:pheral.identifier.UUIDString] ){
        return YES;
    }
    return NO;
}


-(void)startFindSrv:(CBPeripheral*)pheral{

    _peripheral = pheral;
    _peripheral.delegate = self;
    _strBootVer = @"";
    [_peripheral discoverServices:nil];
}

-(void)disConnect:(CBPeripheral*)pheral{
    _peripheral = pheral;
}

#pragma mark 蓝牙连接上的代理 【1】寻找蓝牙服务
//外围设备寻找到服务后
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    if( error ){
        NSLog(@"外围设备寻找服务过程中发生错误，错误信息：%@",error.localizedDescription);
        return;
    }
    
    // 1.查询所有的蓝牙服务
    for (CBService *service in peripheral.services) {
        
        NSLog(@"------发现蓝牙服务：%@",service.UUID.UUIDString);
        if ([service.UUID isEqual:_uuidWR ] ){
            _bIsInOTA = NO;
        }
        [peripheral discoverCharacteristics:nil forService:service];
    }
}



#pragma mark 【7】寻找蓝牙服务中的特性
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    
    if (error) {//报错直接返回退出
        NSLog(@"didDiscoverCharacteristicsForService error : %@", [error localizedDescription]);
        return;
    }
    
    //NSLog(@"---------->服务：%@<------",service.UUID);
    NSLog(@"服务:%@",[service.UUID UUIDString]);
    for (CBCharacteristic *chrtsc in service.characteristics) {//遍历服务中的所有特性
            
            if ([chrtsc.UUID.UUIDString isEqualToString:BLEUUID_SERVER_WR_READ]) {
                NSLog(@"   --------->蓝牙特读征值：%@",chrtsc.UUID.UUIDString );
                [peripheral setNotifyValue:YES forCharacteristic:chrtsc];
                self.readCmdChrtcs = chrtsc;
            }
                
        
            if ([chrtsc.UUID.UUIDString isEqualToString:BLEUUID_SERVER_WR_WRITE] ) {
                NSLog(@"   --------->蓝牙写特征值：%@",chrtsc.UUID.UUIDString );
                NSLog(@"PropertyWrite == %@",chrtsc.UUID.UUIDString);
                [peripheral setNotifyValue:YES forCharacteristic:chrtsc];
                self.writeCmdAckChrtcs = chrtsc;

            }
         
        }
    //读写特征都扫描到了
    if (self.readCmdChrtcs&&self.writeCmdAckChrtcs) {
        
    }
}

#pragma mark 【8】直接读取特征值被更新后  **********读数据*********
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    
    
    if (error) {
        NSLog(@"%@更新特征值时发生错误，错误信息：name=%@ errorDesc=%@",characteristic.UUID.UUIDString,
              peripheral.name,error.localizedDescription);
        return;
    }
    
    //解析数据
    NSLog(@"-------->收到设备数据:%@",characteristic.value);
    NSLog(@"-------->字符串:%@", [JCDataConvert convertHexDataToHexString:characteristic.value]);
    NSDictionary *receiveData = [CBLEDataParse parseReceiveData:characteristic.value];
 
    POST_MSG_WITHOBJ(BLEMSG_PHERAL_SENDMSG_ACK, receiveData);

    NSData *data = [[NSData alloc] initWithData:characteristic.value];
    //NSLog(@"data === %@ len == %ld  UUID=== %@",data,data.length,characteristic.UUID.UUIDString);
    CBLEDataParse *parseTool = [CBLEDataParse dataParse];
    if ([characteristic.UUID.UUIDString isEqualToString:@"2A23"]) {
        //mac地址组装
        NSString *strMacAddr = [parseTool parseMacAddr:characteristic];
        if (strMacAddr.length < 16) {
            return;
        }
        self.adverMacAddr = strMacAddr;
        POST_MESSAGE(BLEMSG_PHERAL_UPDATE_INFO);
    }
    
    if ([characteristic.service.UUID.UUIDString isEqualToString:@"FFE0"]) {
        if ([characteristic.UUID.UUIDString isEqualToString:@"FFE1"]&&data.length>3) {
            NSUInteger ackType = [JCDataConvert oneByteToDecimalUint:[data subdataWithRange:NSMakeRange(1, 1)]];
            NSUInteger cmdType = [JCDataConvert oneByteToDecimalUint:[data subdataWithRange:NSMakeRange(2, 1)]];
            if (ackType == 0x77) {
                if (cmdType == 0x01) {
                    self.isHandleData = NO;
                    NSLog(@"data 1== %@ len == %ld UUID=== %@ ",data,data.length,characteristic.UUID.UUIDString);
                }
                
                if (cmdType == 0x02) {
                    self.isHandleData = NO;
                    NSLog(@"data 2== %@ len == %ld UUID=== %@ ",data,data.length,characteristic.UUID.UUIDString);
                }
                
                if (cmdType == 0x03) {
                    self.isHandleData = NO;
                    NSLog(@"data 3== %@ len == %ld UUID=== %@ ",data,data.length,characteristic.UUID.UUIDString);
                }
                
                ZBLEDataModel *model = [[ZBLEDataModel alloc] initWith:data];
                if (_delegate&&[_delegate respondsToSelector:@selector(reviceAck:ackData:)] ){
                    [self.delegate reviceAck:self ackData:model];
                }else{
                    if (cmdType == 0x01) {
                        self.model1 = model;
                    }
                    if (cmdType == 0x02) {
                        self.model2 = model;
                    }
                }
            }else if (ackType == 0x78){
                NSLog(@"写参数");
                ZBLEhandleDataModel *model = [[ZBLEhandleDataModel alloc] initWith:data];
                if (_delegate&&[_delegate respondsToSelector:@selector(wristAck:ackData:)]) {
                    [self.delegate wristAck:self ackData:model];
                }
            }else if (ackType == 0x79){
                NSLog(@"读参数");
                NSLog(@"data 4== %@ len == %ld UUID=== %@ ",data,data.length,characteristic.UUID.UUIDString);
                ZBLEhandleDataModel *model = [[ZBLEhandleDataModel alloc] initWith:data];
                if (_delegate&&[_delegate respondsToSelector:@selector(wristAck:ackData:)]) {
                    [self.delegate wristAck:self ackData:model];
                }
            }
        }
    
    }
    
    
}


//该方法触发当设备的服务改变时候
- (void)peripheral:(CBPeripheral *)peripheral didModifyServices:(NSArray<CBService *> *)invalidatedServices {
    NSLog(@"服务发生了改变============%@",invalidatedServices);
    for (int i=0; i<invalidatedServices.count; i++) {
//        [self peripheral:peripheral didDiscoverCharacteristicsForService:invalidatedServices[i] ];
        NSLog(@"%@",invalidatedServices[i]);
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    if(error){
        NSLog(@"---->向特征%@发送数据失败:%@",characteristic.UUID.UUIDString,error);
    }else{
        NSLog(@"---->向特征%@发送数据成功",characteristic.UUID.UUIDString);
    }
}



-(void)writeCmdAckMsg:(NSData*)cmdData{
    
    NSString *strCmd = [JCDataConvert convertDataToHexStr:cmdData];
    NSLog(@" ---->app write cmd: %@\n",strCmd );
    
    if ( _bIsInOTA ){
        NSLog(@"------>当前是OTA模式，不能发送wrist命令！<------");
        return;
    }
    if ( _peripheral != nil && _writeCmdAckChrtcs != nil ){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(CMD_SEND_INTERVAL * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.peripheral writeValue:cmdData
                  forCharacteristic:self.writeCmdAckChrtcs
                               type:CBCharacteristicWriteWithResponse];
//            NSLog(@" ------>向设备发送数据:%@ 特征值:%@",cmdData,_writeCmdAckChrtcs.UUID.UUIDString);
        });
    }
}


-(void)readCmdAckMsg:(NSData*_Nullable)cmdData
{
    NSString *strCmd = [JCDataConvert convertDataToHexStr:cmdData];
    NSLog(@" ---->app read cmd: %@\n",strCmd );
    
    if ( _bIsInOTA ){
        NSLog(@"------>当前是OTA模式，不能发送wrist命令！<------");
        return;
    }
    if ( _peripheral != nil && _readCmdChrtcs != nil ){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(CMD_SEND_INTERVAL * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.peripheral writeValue:cmdData
                  forCharacteristic:self.readCmdChrtcs
                               type:CBCharacteristicWriteWithResponse];
//            NSLog(@" ------>向设备发送数据:%@ 特征值:%@",cmdData,_readCmdChrtcs.UUID.UUIDString);
        });
  
    }
}

- (BOOL)wristSsidMsg:(NSData*)data{
    NSString *strCmd = [JCDataConvert convertDataToHexStr:data];
    NSLog(@" -->app cmd: %@",strCmd );
    
    
    if ( _bIsInOTA ){
        NSLog(@"------>当前是OTA模式，不能发送wrist命令！<------");
        return NO;
    }
    if ( _peripheral != nil && _writeSsidCmdAckChrtcs != nil ){
        [_peripheral writeValue:data
              forCharacteristic:_writeSsidCmdAckChrtcs
                           type:CBCharacteristicWriteWithResponse];
        return YES;
    }
    
    return NO;
}

- (BOOL)wristPassMsg:(NSData*)data{
    NSString *strCmd = [JCDataConvert convertDataToHexStr:data];
    NSLog(@" -->app cmd: %@",strCmd );
    
    
    if ( _bIsInOTA ){
        NSLog(@"------>当前是OTA模式，不能发送wrist命令！<------");
        return NO;
    }
    if ( _peripheral != nil && _writePassCmdAckChrtcs != nil ){
        [_peripheral writeValue:data
              forCharacteristic:_writePassCmdAckChrtcs
                           type:CBCharacteristicWriteWithResponse];
        return YES;
    }
    
    return NO;
}


-(void)writeOTACmd:(NSData*)otaCmdData bInOTA:(BOOL)bInOTA{
  
    NSString *strCmd = [JCDataConvert convertDataToHexStr:otaCmdData];
    NSLog(@" -->ota cmd: %@,--- %lu",strCmd ,(unsigned long)otaCmdData.length);
    
    
    if ( bInOTA && !_bIsInOTA ){
        NSLog(@"------>当前是OTA模式，不能发送wrist命令！<------");
        return;
    }
    
    if ( _peripheral != nil && _writeOTAWithRespCharac != nil ){
        NSLog(@"======发送OTA数据");
        [_peripheral writeValue:otaCmdData
              forCharacteristic:_writeOTAWithRespCharac
                           type:CBCharacteristicWriteWithResponse];
    }
}

-(void)writeOTAData:(NSData*)otaData{
    NSLog(@"写OTA数据：%@",otaData);
    [_peripheral writeValue:otaData
          forCharacteristic:_writeOTAWithoutRespCharac
                       type:CBCharacteristicWriteWithoutResponse];
}
@end



////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#import "BleDevice.h"
@interface CDataPheralMnger()
@property (nonatomic, strong) NSMutableArray      *aryPheral;

@property (nonatomic, copy) NSString *filePath;
@end

@implementation CDataPheralMnger
+(instancetype)dataMnger{
    CDataPheralMnger *dataMnger = [[CDataPheralMnger alloc] init];
    return dataMnger;
}

-(NSInteger)totalNums{
    return _aryPheral.count;
}
-(CDataPheralInfo*)dataWithIndex:(NSInteger)nIdx{
    return [_aryPheral objectAtIndex:nIdx];
}

-(NSMutableArray*)aryPheral{
    if ( _aryPheral == nil ){
        _aryPheral = [NSMutableArray array];
    }
    
    return _aryPheral;
}

-(void)removeAll{
    if ( _aryPheral != nil && _aryPheral.count > 0 ){
        [_aryPheral removeAllObjects];
    }
}


-(BOOL)addPheral:(CBPeripheral*)pheral advData:(NSDictionary *)advData RSSI:(NSNumber *)RSSI{
    CDataPheralInfo *data = [CDataPheralInfo dataPheral:pheral advData:advData RSSI:RSSI];
    return [self addPheral:data];
}


-(BOOL)addPheral:(CDataPheralInfo*)data{
    // 1、第一次扫描到的设备，添加进数组中
    if ( self.aryPheral.count == 0 ){
        [self.aryPheral addObject:data];
    } else {
        //2 - 遍历数组中的蓝牙模型，更新原有的数据（主要是更新信号强度）
        for (NSInteger i = 0; i < self.aryPheral.count; i++ ) {
            CDataPheralInfo *interData = [self.aryPheral objectAtIndex:i];
            if ( [data isSamePheral:interData.peripheral] ){
                //更新,不替换,蓝牙配网那里有匹配我的设备列表,会把设备id刷掉
                
                interData.RSSI = data.RSSI;
                interData.adverMacAddr = data.adverMacAddr;
                interData.deviceType   = data.deviceType;
                //不要替换,会把设备id给刷掉
//                [self.aryPheral objectAtIndex:i withObject:data];
                return NO;
            }
        }
        
        // 3 - 若未有包含过此设备，则将其添加进数组中
        if (![self.aryPheral containsObject:data]) {
            [self.aryPheral addObject:data];
        }
    }
    
    //不在这里排序,不然页面会跳动
//    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"RSSI" ascending:NO];
//    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor count:1];
//    [self.aryPheral sortUsingDescriptors:sortDescriptors];
    
    return YES;
}

#pragma mark --------- 保存连接过的蓝牙
-(void)saveBleDevice:(CDataPheralInfo*_Nullable)device
{
    NSArray *dataArr = [self readBleDevice];
    __block BOOL isExist = NO;
    [dataArr enumerateObjectsUsingBlock:^(CDataPheralInfo  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([obj.devName isEqualToString:device.devName]){
            isExist = YES;
            *stop = YES;
        }
    }];
    if(isExist) return;
    device.connectTime = [[NSDate date]timeIntervalSince1970];
    NSMutableArray *arr = [NSMutableArray arrayWithArray:dataArr];
    [arr addObject:device];
    if([NSKeyedArchiver archiveRootObject:arr toFile:self.filePath]){
        NSLog(@"---->保存成功,%@",device.devName);
        POST_MESSAGE(BLEMSG_LOCAL_DEVICE_CHANGE);
    }else{
        NSLog(@"---->保存失败,%@",device.devName);
    }
    
    
}

#pragma mark ---------读取连接过的蓝牙
-(NSArray*)readBleDevice
{
   NSArray *arr =  [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];
    NSLog(@"---->读出的个数:%ld",arr.count);
    return arr;
}

-(void)deleteLocalDevice:(CDataPheralInfo*_Nullable)device
{
    NSArray *dataArr = [self readBleDevice];
    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:dataArr];
    
    [dataArr enumerateObjectsUsingBlock:^(CDataPheralInfo  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([[obj.devName uppercaseString] isEqualToString:[device.devName uppercaseString]]){
            [tempArr removeObjectAtIndex:idx];
            if([NSKeyedArchiver archiveRootObject:tempArr toFile:self.filePath]){
                NSLog(@"---->删除成功");
                POST_MESSAGE(BLEMSG_LOCAL_DEVICE_CHANGE);
            }else{
                NSLog(@"---->删除失败");
            }
            *stop = YES;
        }
    }];

}

//删除全部本地设备
-(BOOL)deleteAllLocalDevices
{
    NSError *error;
    BOOL result = [[NSFileManager defaultManager]removeItemAtPath:self.filePath error:&error];
    if (result) {
        if (error) {
            NSLog(@"---->删除文件失败:%@",error);
            return NO;
        }else{
            NSLog(@"----->删除文件成功");
            return YES;
        }
    }else{
        NSLog(@"---->删除文件失败");
        return NO;
    }
    
}

-(NSString *)filePath
{
    if(!_filePath){
        
        
        NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSString *directorPath = [documentsDirectory stringByAppendingPathComponent:@"blueList"];
        NSString *filePath = [directorPath stringByAppendingPathComponent:@"devices.plist"];

        if(![[NSFileManager defaultManager] fileExistsAtPath:directorPath]){
            if([[NSFileManager defaultManager] createDirectoryAtPath:directorPath withIntermediateDirectories:YES attributes:nil error:nil]){
                NSLog(@"----->创建文件夹成功:%@",directorPath);
                
            }else{
                NSLog(@"----->创建文件夹失败:%@",directorPath);
            }
            
        }else{
            NSLog(@"----->文件夹已存在:%@",directorPath);
            
        }
        if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
            [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
        }else{
            NSLog(@"----->文件已存在:%@",filePath);
        }
        NSArray *resultArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
        for(id obj in resultArray) {
            NSLog(@"浅层遍历文件 = %@",obj);
        }
      
        _filePath = filePath;
    }
    return _filePath;
}

@end

